package a1_reader;


import java.io.*;
import java.util.HashMap;

import a1_graph_lib.AIGraph;

public class GraphReader {

	public static String ist_ungerichtet = "#ungerichtet";
	public static String ist_gerichtet = "#gerichtet";
	public int nicht_erfolgreich = -1;

	public static void main() {
		System.out.println("Start");
		AIGraph new_graph = new AIGraph();
		readGraph(new_graph, "graph1.txt");
		System.out.println("Ready");
	}

	public static AIGraph readGraph(AIGraph graph, String textfile) {

		HashMap<String, Integer> name_list = new HashMap<String, Integer>();
		AIGraph new_graph = new AIGraph();

		String zeile = null;

		int v1;
		int v2;
		int e1;
		int attr_anzahl;
		int attr_nummer = 0;
		int possibel_int;

		boolean gerichtet = false;
		boolean first_line = true;

		try {
			BufferedReader in = new BufferedReader(new FileReader(textfile));
			while ((zeile = in.readLine()) != null) {
				// Bestimmt ob der Graph Gerichtet oder Ungerichtet ist
				if (first_line) {
					if (zeile.equals(ist_gerichtet)) {
						gerichtet = true;
						first_line = false;
					} else if (zeile.equals(ist_ungerichtet)) {
						gerichtet = false;
						first_line = false;
					} else {
						throw new IllegalArgumentException(
								"Reader: Richtung des Graphen nicht angegeben");
					}
				} else {

					String[] parts = zeile.split(",");

					if (name_list.containsKey(parts[0])) {
						v1 = name_list.get(parts[0]);
					} else {
						v1 = new_graph.addVertex(parts[0]);
						name_list.put(parts[0], v1);
						new_graph.setStrV(v1, "NAME", parts[0]);
					}

					if (name_list.containsKey(parts[1])) {
						v2 = name_list.get(parts[1]);
					} else {
						v2 = new_graph.addVertex(parts[1]);
						name_list.put(parts[1], v2);
						new_graph.setStrV(v2, "NAME", parts[1]);
					}

					if (gerichtet) {
						e1 = new_graph.addEdgeD(v1, v2);
					} else {
						e1 = new_graph.addEdgeU(v1, v2);
					}
					attr_anzahl = parts.length - 2;
					attr_nummer = 0;

					while (attr_anzahl > 0) {
						try {
							possibel_int = Integer
									.parseInt(parts[attr_nummer + 2]);
							new_graph.setValE(e1,
									(new Integer(attr_nummer)).toString(),
									possibel_int);
						} catch (NumberFormatException ex) {
							new_graph.setStrE(e1,
									(new Integer(attr_nummer)).toString(),
									parts[attr_nummer + 2]);
						}
						attr_anzahl = attr_anzahl - 1;
						attr_nummer = attr_nummer + 1;
					}

				}
			}
		in.close();	
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return new_graph;
	}

}
